<template>
	<div class="login-container">
		<div class="login-content-left" v-if="!state.isDingTalk">
			<div class="login-logo">
				<span>xMagic</span>
			</div>
			<div style="width: 350px">
				<Mobile v-if="state.isTabPaneShow" />
				<Account v-else />
			</div>
			<div style="display: flex; justify-content: flex-start; width: 100%">
				<span class="login-content-left-change" @click="onTabsClick">{{ state.isTabPaneShow ? '账号登录' : '免密登录'
					}}<el-icon>
						<CaretRight />
					</el-icon></span>
			</div>
		</div>
		<div class="login-content-right">
			<!-- 二维码展示 -->
			<div class="qr-text" v-if="!state.isDingTalk">支持钉钉/云上开投</div>
			<div class="qr-text" v-if="state.isDingTalk">长按下方二维码<br>进行识别登录</div>
			<div style="width: 166px;height: 166px;position: relative;">
				<qrcode-vue3 v-if="state.qrValue" :value="state.qrValue" :width="166" :height="166"
					:qrOptions="{ typeNumber: 0, mode: 'Byte', errorCorrectionLevel: 'L' }"
					:imageOptions="{ hideBackgroundDots: true, imageSize: 0.1, margin: 0 }"
					:dotsOptions="{ type: 'square', color: '#000', gradient: { type: 'linear', rotation: 0, colorStops: [{ offset: 0, color: '#000' }, { offset: 1, color: '#000' }] } }"
					:backgroundOptions="{ color: '#ffffff' }"
					:cornersSquareOptions="{ type: 'square', color: '#000000' }"
					:cornersDotOptions="{ type: undefined, color: '#000000' }" fileExt="png" imgclass="img-qr" />
				<div class="mask" @click="handleRefresh" v-show="state.isExpired">
					<div style="margin-bottom: 10px;"><i class="fc-icon fc-icon-refresh" style="font-size: 60px;"></i>
					</div>
					<div>二维码已过期</div>
					<div>点击刷新</div>
				</div>
			</div>
			<div class="qr-text" v-if="!state.isDingTalk">
				<div>推荐使用<a target="_blank"
						href="https://download.dingtalk.com/guest/welcome?uuid=499b908e-0082-4ce7-bc44-477e9f96c1ad448&type=pc">云上开投</a>手机APP
				</div>
				<div>扫描二维码快速登录</div>
			</div>
		</div>
	</div>
	<div class="footer-container">
		<div class="icp-text" onclick="window.open('https://beian.miit.gov.cn/')">蜀ICP备14009466号</div>
	</div>
</template>

<script setup lang="ts">
import { reactive, computed, onMounted, getCurrentInstance } from 'vue';
import Account from '@/views/login/component/account.vue';
import Mobile from '@/views/login/component/mobile.vue';
import QrcodeVue3 from 'qrcode-vue3';
import { ElMessage } from 'element-plus';
import { initBackEndControlRoutes } from '@/router/index';
import { formatAxis } from '@/utils/formatTime';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const { proxy } = getCurrentInstance() as any;
const route = useRoute();
const router = useRouter();
const state = reactive({
	tabsActiveName: 'account',
	isTabPaneShow: true,
	isDingTalk: false,
	qrValue: '',
	isExpired: false,
});
// 切换密码、手机登录
const onTabsClick = () => {
	state.isTabPaneShow = !state.isTabPaneShow;
};
// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 刷新二维码
const handleRefresh = () => {
	subscribeQrcode()
}
// 登录成功后的跳转
const signInSuccess = () => {
	// 初始化登录成功时间问候语
	let currentTimeInfo = currentTime.value;
	// 登录成功，跳到转首页
	// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
	// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
	if (route.query.redirect) {
		router.push({
			path: route.query?.redirect as string,
			query: Object.keys(route.query?.params).length > 0 ? JSON.parse(route.query?.params) : '',
		});
	} else {
		router.push('/');
	}
	//登录成功提示
	setTimeout(() => {
		const signInText = t('message.signInText');
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 修复防止退出登录再进入界面时，需要刷新样式才生效的问题，初始化布局样式等(登录的时候触发，目前方案)
		proxy.mittBus.emit('onSignInClick');
	}, 300);
};

const subscribeQrcode = () => {
	let eventSource = new EventSource(`/api/user/oauth/dingtalk/qrcode`);
	// 处理自定义事件
	eventSource.addEventListener('success', async (event) => {
		ElMessage({
			type: 'success',
			message: event.data
		})
		eventSource.close();
	});
	eventSource.addEventListener('info', async (event) => {
		ElMessage({
			type: 'success',
			message: event.data
		})
	});
	eventSource.addEventListener('login', async (event) => {
		const customData = JSON.parse(event.data);
		localStorage.setItem('expire', customData.expire);
		await fetch(`/api/user/oauth/secret/${customData.secret}`)
		// 处理 callback 重定向
		if (route.query.callback) {
			window.location.href = route.query.callback + '?secret=' + customData.secret;
			return;
		}
		await initBackEndControlRoutes();
		signInSuccess();
	});
	eventSource.addEventListener('data', async (event) => {
		if (sessionStorage.getItem('userInfo')) {
			// 关闭连接
			eventSource.close();
			return
		}
		const customData = JSON.parse(event.data);
		state.qrValue = ''
		state.qrValue = customData.url
		state.isExpired = false
	});
	eventSource.addEventListener('panic', async (event) => {
		if (sessionStorage.getItem('userInfo')) {
			// 关闭连接
			eventSource.close();
			return
		}
		state.isExpired = true
		ElMessage({
			type: 'error',
			message: event.data
		})
		eventSource.close();
	});
	eventSource.addEventListener('error', async (event) => {
		eventSource.close();
		eventSource = new EventSource(`/api/user/oauth/dingtalk/qrcode`);
	});

}

const isDingTalk = () => {
	return navigator.userAgent.indexOf('DingTalk') !== -1;
};

onMounted(() => {
	state.isDingTalk = isDingTalk();
	subscribeQrcode()
})
</script>

<style scoped lang="scss">
.login-container {
	width: 100%;
	height: 100%;
	background-size: 100% 100%;
	background: #fff;
	display: flex;
	justify-content: center;
	gap: 50px;
	align-items: center;

	.login-content-left {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		border-right: 1px solid #ddd;
		padding-right: 30px;

		.login-content-left-change {
			color: #687483;
			letter-spacing: 2px;
			cursor: pointer;
			display: flex;
			align-items: center;

			&:hover {
				color: var(--color-primary);
			}
		}
	}

	.login-content-right {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.mask {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: #4d4d4d99;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			color: #fff;
			cursor: pointer;
		}
	}

	.qr-text {
		margin: 22px auto;
		font-size: 14px;
		color: #474747;
		min-width: 300px;
		text-align: center;
	}


	.login-logo {
		height: 50px;
		color: var(--color-primary);
		letter-spacing: 2px;
		width: 100%;
		margin-bottom: 20px;

		>span {
			font-size: 35px;
			font-weight: bold;
			line-height: 50px;
			color: var(--color-primary);
			letter-spacing: 2px;
		}

	}

	.login-content {
		width: 500px;
		padding: 20px;
		position: absolute;
		top: 50%;
		left: 80%;
		transform: translate(-50%, -50%) translate3d(0, 0, 0);
		background-color: rgba(255, 255, 255, 0.99);
		border: 5px solid var(--color-primary-light-8);
		border-radius: 4px;
		transition: height 0.2s linear;
		height: 520px;
		overflow: hidden;
		transition: all 0.3s ease;
		z-index: 1;

		.login-content-main {
			margin: 0 auto;
			width: 80%;

			.login-content-title {
				color: #333;
				font-weight: 500;
				font-size: 22px;
				text-align: center;
				letter-spacing: 4px;
				margin: 15px 0 30px;
				white-space: nowrap;
				z-index: 5;
				position: relative;
				transition: all 0.3s ease;
			}
		}

		.login-content-icon {
			font-size: 25px;
			margin-right: 30px;
		}

		.login-content-main-sacn {
			position: absolute;
			top: 0;
			right: 0;
			width: 50px;
			height: 50px;
			overflow: hidden;
			cursor: pointer;
			transition: all ease 0.3s;

			&-delta {
				position: absolute;
				width: 35px;
				height: 70px;
				z-index: 2;
				top: 2px;
				right: 21px;
				background: var(--el-color-white);
				transform: rotate(-45deg);
			}

			&:hover {
				opacity: 1;
				transition: all ease 0.3s;
				color: var(--color-primary);
			}

			i {
				width: 47px;
				height: 50px;
				display: inline-block;
				font-size: 48px;
				position: absolute;
				right: 2px;
				top: -1px;
			}
		}
	}

	.login-content-mobile {
		height: 460px;
	}

	.login-copyright {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 30px;
		text-align: center;
		color: var(--color-whites);
		font-size: 12px;
		opacity: 0.8;

		.login-copyright-company {
			white-space: nowrap;
		}

		.login-copyright-msg {
			@extend .login-copyright-company;
		}
	}
}

.icp-text {
	position: fixed;
	bottom: 0px;
	right: 0px;
	color: gray;
	font-size: 7px;
	text-align: right;
	padding: 20px;
}
</style>
